package com.snts.synchronization.core;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

public class ChangeColumn {

	Column column;
	private boolean on = true;
	private Object value;

	public ChangeColumn(Column column) {
		this(column, true);
	}

	public ChangeColumn(Column column, boolean on) {
		super();
		this.column = column;
		this.on = on;
	}

	public Column getColumn() {
		return column;
	}

	public void setOn(boolean on){
		this.on = on;
	}

	public boolean isOn() {
		return on;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}
	
	public void setAsString(String value){
		switch(getColumn().getSqlType()){
		case Types.INTEGER:
			setValue(new Integer(value));
			break;
		case Types.SMALLINT:
			setValue(new Short(value));
			break;
		case Types.BOOLEAN: case Types.BIT:
			setValue("1".equals(value) ? (short) 1 : (short) 0);
			break;
		case Types.VARCHAR: case Types.CHAR:
			setValue(value);
			break;
		case Types.OTHER:
			if("uuid".equals(getColumn().getTypeName())){
				setValue(java.util.UUID.fromString(value));
			}
		default:
			setValue(value);
			break;
		}
	}

	@Override
	public String toString() {
		return "ChangeColumn [column=" + column + ", on=" + on + ", value=" + value + "]";
	}
	
	public void setParam(PreparedStatement pstmt, int paramIndex) throws SQLException {
		if(column.getSqlType() == Types.BIT){
			pstmt.setBoolean(paramIndex++, (short) getValue() == 1 ? true : false);
		} else {
			pstmt.setObject(paramIndex++, getValue());
		}
	}

}
